package com.kaka.bluetoothble;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.common.eventbus.Subscribe;
import com.kaka.bluetoothble.adapter.BleAdapter;
import com.kaka.bluetoothble.base.BaseActivity;
import com.yunlin.bean.BleDevice;
import com.yunlin.bean.OpenLockStatus;
import com.yunlin.blecontroler.BleController;
import com.yunlin.blecontroler.IBteScanConnectListner;
import com.yunlin.event.ReadDeviceInfoEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import de.greenrobot.event.EventBus;

public class MainActivity extends BaseActivity{
    
    private static String TAG="MainActivity";
    
    
    @BindView(R.id.ivSerBleStatus) ImageView ivSerBleStatus;
    @BindView(R.id.tvSerBleStatus) TextView tvSerBleStatus;
    @BindView(R.id.tvSerBindStatus) TextView tvSerBindStatus;
    @BindView(R.id.rl_bluetooth) RelativeLayout rlBluetooth;
    @BindView(R.id.bleListView) ListView bleListView;
    @BindView(R.id.tvResponse) TextView tvResponse;
    @BindView(R.id.operaView) LinearLayout operaView;
    @BindView(R.id.tv_battery) TextView tv_battery;
    @BindView(R.id.tv_voice) TextView tv_voice;
    @BindView(R.id.tv_voltage) TextView tv_voltage;
    
    @BindView(R.id.ll_open_lock) LinearLayout ll_open_lock;
    @BindView(R.id.ll_device_info) LinearLayout ll_device_info;
    @BindView(R.id.ll_admin_verify) LinearLayout ll_admin_verify;
    
    private BleController bleController;
    private List<BleDevice> bleDevices;
    private BleAdapter mAdapter;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_device);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initDatas();
        bleController.setCurrentFunctionMode(BleController.FUNCTION_OPEN_LOCK);
    }
    
    
    @OnClick(R.id.ll_admin_verify)
    public void ll_admin_verify(){
        bleController.setCurrentFunctionMode(BleController.FUNCTION_VERIFY_ADMIN);
        connectItem(0);
    }
    
    @OnClick(R.id.ll_open_lock)
    public void ll_open_lock(){
        bleController.setCurrentFunctionMode(BleController.FUNCTION_OPEN_LOCK);
        connectItem(0);
    }
    
    @OnClick(R.id.ll_device_info)
    public void ll_device_info(){
        bleController.setCurrentFunctionMode(BleController.FUNCTION_READ_BATTERY_INFO);
        connectItem(0);
    }
    
    private void initDatas(){
        bleController=new BleController(MainActivity.this, new IBteScanConnectListner(){
            
            @Override
            public void onScanResult(final List<BleDevice> scanedDevices){
                runOnUiThread(() -> {
                    if (null != scanedDevices && scanedDevices.size() > 0) {
                        notifyBleDeviceDataChanges(scanedDevices);
                        ll_admin_verify.setEnabled(true);
                        ll_device_info.setEnabled(true);
                        ll_open_lock.setEnabled(true);
                    }
                });
            }
            
            @Override
            public void onReiceveBleDeviceDat(OpenLockStatus openLockStatus){
                runOnUiThread(() -> showBleDeviceSendData(openLockStatus));
            }
            
            
            @Override
            public void onBleConnect(){
                runOnUiThread(() -> setBleConnected());
            }
            
            @Override
            public void onBleBusy(){
                runOnUiThread(() -> {
                    tvSerBindStatus.setText("设备忙碌 请等3秒钟");
                });
            }
            
            @Override
            public void onOtheDeviceIsConnecting(){
                runOnUiThread(() -> {
                    tvSerBindStatus.setText("其他设备正在连接，请等待。。。");
                });
            }
            
            //连接断开
            @Override
            public void onBleDisConnect(){
                runOnUiThread(() -> {
                    bleListView.setEnabled(true);
                    tvSerBindStatus.setText("已断开链接，请重新链接设备");
                });
            }
            
            @Override
            public void needReScan(){
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "请重新扫描设备", Toast.LENGTH_SHORT).show();
                    bleListView.setEnabled(true);
                    bleListView.setBackgroundResource(R.drawable.shape_list_item_enable);
                });
            }
            
            @Override
            public void onConnectTimeOut(){
                runOnUiThread(() -> {
                    bleListView.setEnabled(true);
                    bleListView.setBackgroundResource(R.drawable.shape_list_item_enable);
                    tvSerBindStatus.setText("连接设备超时，请稍后重试");
                });
            }
        });
        bleController.init();
        bleDevices=new ArrayList<>();
        mAdapter=new BleAdapter(MainActivity.this, bleDevices);
        bleListView.setAdapter(mAdapter);
    }
    
    void setBleConnected(){
        operaView.setVisibility(View.VISIBLE);
        tvSerBindStatus.setText("已连接");
    }
    
    @Override
    protected void onPause(){
        super.onPause();
        bleController.stopScan();
        if (bleDevices != null) {
            bleDevices.clear();
        }
    }
    
    void showBleDeviceSendData(OpenLockStatus openLockStatus){
        if (openLockStatus == null) {
            return;
        }
        if (openLockStatus.isOpenSuccess()) {
            tvResponse.setText("开锁成功" + "耗时 ：" + openLockStatus.getUseTime());
            bleListView.setEnabled(true);
        }else {
            tvResponse.setText("开锁失败" + "耗时 ：" + openLockStatus.getUseTime());
        }
        bleListView.setEnabled(true);
        bleListView.setBackgroundResource(R.drawable.shape_list_item_enable);
    }
    
    
    @Subscribe
    public void onEventMainThread(ReadDeviceInfoEvent readDeviceInfoEvent){
        tv_voice.setText(readDeviceInfoEvent.getVoiceStr());
        tv_battery.setText(readDeviceInfoEvent.getBatteryStr());
        tv_voltage.setText(readDeviceInfoEvent.getVoltageStr());
        bleController.releaseConnect(true);
        bleListView.setEnabled(true);
        bleListView.setBackgroundResource(R.drawable.shape_list_item_enable);
    }
    
    public void notifyBleDeviceDataChanges(List<BleDevice> scanedDeviced){
        if (null == bleDevices) {
            bleDevices=new ArrayList<>();
        }
        this.bleDevices.clear();
        this.bleDevices.addAll(scanedDeviced);
        mAdapter.notifyDataSetChanged();
    }
    
    @OnItemClick(R.id.bleListView)
    public void bleListViewItemClicked(AdapterView<?> parent, View view, int position, long id){
        connectItem(position);
    }
    
    private void connectItem(int position){
        
        
        ll_admin_verify.setEnabled(false);
        ll_device_info.setEnabled(false);
        ll_open_lock.setEnabled(false);
        
        if (bleDevices.size() < 0) {
            return;
        }
        tvResponse.setText("");
        runOnUiThread(() -> tvSerBindStatus.setText("正在连接"));
        bleListView.setEnabled(false);
        bleListView.setBackgroundResource(R.drawable.shape_list_item_unable);
        bleController.connectDevice(bleDevices.get(position), false);
    }
    
    @OnClick(R.id.ivSerBleStatus)
    public void ivSerBleStatus(){
        if (bleController.isScaning()) {
            return;
        }else {
            scanDevice();
        }
    }
    
    private static final int REQUEST_BLUTOOTH_CODE=22;
    
    private void scanDevice(){
        
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                                              REQUEST_BLUTOOTH_CODE);
//判断是否需要 向用户解释，为什么要申请该权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                                                                    Manifest.permission.READ_CONTACTS)) {
                Toast.makeText(this, "shouldShowRequestPermissionRationale", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        
        setScaningStatuAndexecuteScan();
    }
    
    private void setScaningStatuAndexecuteScan(){
        if (bleDevices == null) {
            bleDevices=new ArrayList<>();
        }
        tvSerBindStatus.setText("正在搜索");
        operaView.setVisibility(View.GONE);
        bleListView.setVisibility(View.VISIBLE);
        bleDevices.clear();
        bleController.setIsScaning(true);
        tvResponse.setText("");
        bleController.releaseConnect(false);
    }
    
    
    @Override
    protected void onResume(){
        super.onResume();
        tvSerBindStatus.setText("正在扫描");
        bleController.scanBteLockDevice();
        bleListView.setEnabled(true);
        bleListView.setBackgroundResource(R.drawable.shape_list_item_enable);
    }
    
    
    @Override
    protected void onDestroy(){
        super.onDestroy();
        bleController.releaseConnect(false);
        EventBus.getDefault().unregister(this);
    }
    
    @Override
    public void onBackPressed(){
        super.onBackPressed();
        Log.i(TAG, " back click here");
        if (bleController != null) {
            bleController.destoryBle();
        }
        bleDevices.clear();
        bleDevices=null;
        Log.i(TAG, " destory the  bleController and clear the listBlueDevice ");
        finish();
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        switch (requestCode) {
            case REQUEST_BLUTOOTH_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户同意授权
                    setScaningStatuAndexecuteScan();
                }else {
                    //用户拒绝授权
                }
                break;
        }
    }
    
}
